﻿using System;
using System.Diagnostics;
using System.Windows.Input;

namespace AttachedCommands.ACB
{
    public class RelayCommand : ICommand
    {
        #region Fields

        public Predicate<object> CanExecuteDelegate;
        public Action<object> ExecuteDelegate;

        #endregion // Fields

        #region Constructors

        /// <summary>
        /// Creates a new command that can always ExecuteDelegate.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        public RelayCommand(Action<object> execute)
            : this(execute, null)
        {
        }

        /// <summary>
        /// Creates a new command.
        /// </summary>
        /// <param name="execute">The execution logic.</param>
        /// <param name="canExecute">The execution status logic.</param>
        public RelayCommand(Action<object> execute, Predicate<object> canExecute)
        {
            if (execute == null)
                throw new ArgumentNullException("execute");

            ExecuteDelegate = execute;
            CanExecuteDelegate = canExecute;
        }

        #endregion // Constructors

        #region ICommand Members

        [DebuggerStepThrough]
        public bool CanExecute(object parameter)
        {
            return CanExecuteDelegate == null ? true : CanExecuteDelegate(parameter);
        }

        public event EventHandler CanExecuteChanged
        {
            add { CommandManager.RequerySuggested += value; }
            remove { CommandManager.RequerySuggested -= value; }
        }

        public void Execute(object parameter)
        {
            if (ExecuteDelegate != null)
                ExecuteDelegate(parameter);
        }

        #endregion
    }
}
